<?php

namespace App\Models\Admin;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;

class Sms {
	/**
	 * 请求消息中心
	 */
	private function _msg_post($url , $post){
		$base_url =  Config::get('app.msg.URL');
		$key      = Config::get('app.msg.KEY');
		$URL      = $base_url.$url;
		$merchant_no = $post['MerchantNo'];

		$public_data = array(
			'Version'      => '1', // 版本号
			'TimeStamp'    => time()*1000, // 时间戳
			'ClientSystem' => $_SERVER['REMOTE_ADDR'], 
			'ClientSource' => '4',
		);

		// 将公共参数+接口自定义参数 组合起来.转成json
		$data      = array_merge($post,$public_data );
		$json_data = json_encode($data);
		// 生成sign
		$sign      = md5($json_data.$key);

		// 接口请求参数
		$post_data = array(
			'MerchantNo' => $merchant_no,
			'Sign'       => $sign,
			'Json'       => $json_data,
		);
		$sResult = $this->curl_post($URL , $post_data);
		return $sResult;


		// $base_url    = Config::get('app.msg.URL');
		// $URL         = $base_url.$url;
		// $key         = Config::get('app.msg.KEY');
		// // return $URL;
		// $merchant_no = $post['MerchantNo'];
		// $key         = Config::get('app.msg'.strtoupper($merchant_no));
		// $public_data = array(
		// 	'Version'      => '1', // 版本号
		// 	'TimeStamp'    => time()*1000, // 时间戳
		// 	// 'ClientSource' => '4',
		// 	// 'ClientSystem' => $this->get_client_ip(),
		// 	// 'ClientSystem' => '183.38.222.216',
		// 	// 'ClientSystem' => $_SERVER['REMOTE_ADDR'],
		// );
		// // return $public_data;
		// // 将公共参数+接口自定义参数 组合起来.转成json
		// $data      = array_merge($post,$public_data);
		// $json_data = json_encode($data);
		// return $json_data;
		// // 生成sign
		// $sign = md5($json_data.$key);

		// // 接口请求参数
		// $post_data = array(
		// 	'MerchantNo' => $merchant_no,
		// 	'Sign'       => $sign,
		// 	'Json'       => $json_data,
		// );
		// // return $post_data;
		// $sResult = $this->curl_post($URL , $post_data);
		// return $sResult;
	}

	public function curl_post($url,$post_data = array() , $header = false){
		$ch = curl_init(); //初始化curl
		curl_setopt($ch, CURLOPT_URL, $url);//设置链接
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
		curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式
		if($header){
			curl_setopt($ch, CURLOPT_HEADER, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		}
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));//POST数据
		$response = curl_exec($ch);//接收返回信息
		if(curl_errno($ch)){	//出错则显示错误信息
			print curl_error($ch);
		}
		curl_close($ch); //关闭curl链接
		return $response;
	}


	/**
	 * 获取客户端IP地址
	 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
	 * @param boolean $adv 是否进行高级模式获取（有可能被伪装） 
	 * @return mixed
	 */
	public function get_client_ip($type = 0,$adv=false) {
	    $type       =  $type ? 1 : 0;
	    static $ip  =   NULL;
	    if ($ip !== NULL) return $ip[$type];
	    if($adv){
	        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
	            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
	            $pos    =   array_search('unknown',$arr);
	            if(false !== $pos) unset($arr[$pos]);
	            $ip     =   trim($arr[0]);
	        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
	            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
	        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
	            $ip     =   $_SERVER['REMOTE_ADDR'];
	        }
	    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
	        $ip     =   $_SERVER['REMOTE_ADDR'];
	    }
	    // IP地址合法验证
	    $long = sprintf("%u",ip2long($ip));
	    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
	    return $ip[$type];
	}

	/**
	 * 发送消息
	 * @param $mobile 接收者mobile或手机号
	 * @param $title 消息标题
	 * @param $body 消息内容，为消息中心需要接收的那种格式，有模版的
	 * @param string $type 推送方式 用数组传进来 默认为全部推送，例：['wechat','mobile']
	 */
	public function msg($mobile, $title , $body , $type = 'all'){
		$send_type = [
			'mobile', // 手机短信
			'app', // app推送
			'wechat', // 微信推送
			'web', // 站内信
		];
		if('all' == $type){
			$type = $send_type;
		}

		if(!is_array($type)) {
			$push_type = $type;
		}else {
			$push_type = array_intersect($send_type , $type);
		}
		$push_type = ['mobile'];

		$receiver  = '';
		$merchant  = Config::get('app.msg.CH_MERCHANT'); // 默认为普通短信商户号

		if(in_array('mobile' , $push_type)) { // 手机消息推送
			// 每个短信通道的商户号不一样
			$pre    = '';
			$mobile = $mobile;
			// 如果手机号是8位的,则为香港手机号
			if(8 == strlen($mobile) && preg_match('/\d{8}$/',$mobile)) {
				$pre = '00852';
				$merchant = Config::get('app.msg.INTERNATIONAL_MERCHANT');
			} else if(11 == strlen($mobile) && preg_match('/1\d{10}$/',$mobile)){
				$merchant = Config::get('app.msg.CH_MERCHANT');
			}
			$receiver = $pre.$mobile;
		}
		if(in_array('app' , $push_type)) { // app推送
		}
		if(in_array('web' , $push_type)) { // 站内信
		}
		if(in_array('wechat' , $push_type)) { // 微信推送
		}

		$post = array(
				'Title'      => $title,
				'Body'       => array(array(
				'TemplateNo' => $body['TemplateNo'], //邮件模版编号，手机信息模版编号，微信信息编号
				'Receiver'   => $receiver,
				'Parameter'  => $body,
				'SendTime'   => date('Y-m-d H:i:s'),
			)),
			'MerchantNo'     => $merchant,
		);
		// return $post;
		$result = $this->_msg_post('send/index', $post);
		return $result;
	}

	/**
	 * @param $Title 标题
	 * @param $TemplateNo 模版编号 消息中心编辑好的
	 * @param $Receiver 短信则为手机号、微信则为OpenID、邮件则为邮件地址
	 * @param $Parameter body参数
	 * @param $node_id
	 * @param $extras 改参数为app推送的扩展参数
	 * @return mixed
	 */
	public function msgcenter($Title,$TemplateNo,$Receiver,$Parameter,$node_id,$extras = array('key'=>'value')){
		//默认值 data=> {"type":"4"} 跳转到站内消息列表
		if($extras['key'] == 'value') {
			$extras = array('data'=> json_encode(array('type' => 4)));
		}
		// if(in_array($Receiver,$mobile)){
		// 	return false;
		// }
		
		//发送手机短信和微信推送
		$result = false;
		if($Receiver){
			// t18_user_tree 虚拟用户和一些指定手机号和开头19/166，都不发送短信
			// $DUT = D('T18UserTree');
			// $invite_type = $DUT->alias('ut')->join('tnet_reginfo r on r.nodeid = ut.node_id')->where(array('r.nodecode'=>$Receiver))->find();
			// if($invite_type['invite_type'] == '2' || substr($Receiver,0,2) == '19' || substr($Receiver,0,1) == '2' || substr($Receiver,0,3) == '166'){
			// 	return false;
			// }
			$post = array(
				'Title' => $Title,
				'Body'  => array(array(
					'TemplateNo' => $TemplateNo, //邮件模版编号，手机信息模版编号，微信信息编号
					'Receiver'   => $Receiver,
					'Parameter'  => $Parameter,
					'SendTime'   =>date('Y-m-d H:i:s'),
				)),
			);
			
			$URL = "Send/Index";
			$post['MerchantNo'] = C('MSG.MERCHANT'); //商户号
			$post['ClientSource'] = '4';
			$post['ClientSystem'] = get_client_ip();
			$result = $this->_msg_post($URL , $post);
		}
		
		/**
		 *  APP推送
		 * $Receiver不是手机号的时候才执行APP推送，因为注册时$Parameter是一个对象 会引起下面数组报错
		 **/
		if(!is_numeric($Receiver)){
			$push_tags_array = array(
				'3375928039a36520b339a1c7392ef823' => '亲爱的客户，您已充值金额：' .$Parameter['amount']. '到账，请到现金钱包查看。', //帐号充值成功
				'6bd5adfcebf63a9269bd084245824e5d' => '您成功分销出一笔订单,订单号:' .$Parameter['keyword1']. '订单金额：' .$Parameter['keyword2']. '。' .$Parameter['remark'], //分销订单通知
				'7325f9b0d29976cc6b0ecb573e85bb3d' => $Parameter['first']. '。退款金额：' .$Parameter['refund']. '。' .$Parameter['remark'], //订单维权
				'3813199bef7ef726c0b8ca19a2651787' => $Parameter['first']. '。结算类型：' .$Parameter['keyword1']. '。结算金额：' .$Parameter['keyword3'], // 订单结算
				'2f3c8fcb3222d46c3ce1f47a7cd942b8' => $Parameter['first']. '。订单编号：' .$Parameter['keyword1']. '。订单商品：' .$Parameter['keyword2']. '。' .$Parameter['remark'], // 订单自动确认收货
				'2f5f916282fd6d7297550863ceb66d34' => $Parameter['first']. '。红包金额' .$Parameter['keyword4']. ',' .$Parameter['remark'], // 红包
			);
			if(in_array($TemplateNo, array_keys($push_tags_array))) {
				$content = $push_tags_array[$TemplateNo];
				$this->push_tags($Title,$content,$node_id,$extras);
			}
		}
		
		return $result;
	}

	/**
	 * @param int $node_id 或者手机号
	 * @param string $title
	 * @param string $description
	 * @param bool $mobile_message		// 是否同时发送手机短信
	 * 给用户发送站内信
	 * $description <<<EOT
	 * 	内容用这种格式编辑
	 * EOT;
	 */
	public function send_msg($node_id,$title,$description='',$mobile_message = false) {
		$DTM = D('TmsgMessages');
		$DTR = D('TnetReginfo');
		$next_id = $DTM->getNextSeq();
		//如果11位则为手机号
		if(strlen($node_id) == 11){
			$node_id = $DTR->where("nodecode = '$node_id'")->find()['nodeid'];
		}
		$add = array(
			'id'	=> $next_id,
			'owner_id'	=> $node_id,
			'title'	=> $title,
			'content'	=> $description,
		);
		$var = $DTM->add($add);
		return $var ? $next_id : false;
	}

	/**
	 * @param string $platform  安卓传android,苹果传ios,所有all
	 * @param $title  推送标题
	 * @param $content 推送内容
	 */
	public function push($platform='all',$title,$content){
		exit('此接口暂时关闭');
		$jpush = C('JPUSH');
		Vendor('JPush.Client');
		//默认日志路径为 ./jpush.log,即保存在当前运行目录，如果想关闭日志，可以指定为 null
		$client = new \JPush\Client($jpush['app_key'],$jpush['secret'],null);
		$push = $client->push();
		try {
			$push->setPlatform($platform);
			$push->addAllAudience();
			
			switch ($platform) {
				case 'all': { //所有平台
					$push->androidNotification($content, [
						'sound' => 'sound',
						'badge' => '+1',
						'extras' => [
							'key' => 'value'
						],
						'available' => true,
						'title' => $title,//推送标题
						'builder_id' => 0,
					]);
					$push->iosNotification($content, [
						'sound' => 'sound',
						'badge' => '+1',
						'extras' => [
							'key' => 'value'
						],
						'title' => $title,
					]);
					break;
				}
				case 'android': { //安卓平台
					$push->androidNotification($content, [
						'sound' => 'sound',
						'badge' => '+1',
						'extras' => [
							'key' => 'value'
						],
						'available' => true,
						'title' => $title,//推送标题
						'builder_id' => 0,
					]);
					break;
				}
				case 'ios': { //苹果平台
					$push->iosNotification($content, [
						'sound' => 'sound',
						'badge' => '+1',
						'extras' => [
							'key' => 'value'
						],
						'title' => $title,
					]);
					break;
				}
			}
			$result = $push->send();
		}catch (\Exception $e){
			$result = $e.getMessage();
		}
		filedebug('所有推送','./log/app_push.php');
		filedebug($result,'./log/app_push.php');

		//推送成功就执行入库操作
		if($result['http_code'] === 200){
			$params = array(
				'platform' => $platform,
				'title' => $title,
				'content'=> $content
			);
			$data = serialize($params);
		}

	}

	/**
	 * 苹果目前只能用正式appkey和secret 需等他们再创建一个开发者帐号用于测试
	 * @param $title  推送标题 ios无title参数
	 * @param $content 推送内容
	 * Tag 需要和安卓ios商量对应
	 * 如果客户端没有tag值为空极光服务端会抛出cannot find user by this audience
	 */
	public function push_ios_tags($title,$content,$nodeid){
		$app_key = '6ab661912932219d9d174c8d';
		$secret = 'd2a562c9972cbc17f6b17241';
		Vendor('JPush.Client');
		//默认日志路径为 ./jpush.log,即保存在当前运行目录，如果想关闭日志，可以指定为 null
		$client = new \JPush\Client($app_key,$secret,null);
		$push = $client->push();
		try {
			$push->setPlatform('all');
			$push->addTag($nodeid);

			//ios
			$push->iosNotification($content, [
				'sound' => 'sound',
				'badge' => '+1',
				'extras' => [
					'key' => 'value'
				],
				'title' => $title,
				//'content-available' => 1, //为1表示静默推送
			]);
			$push->options(array(
				"sendno" => time(),
				"time_to_live" => 86400, //保存离线时间的秒数默认为一天
			));

			$result = $push->send();
		}catch (\Exception $e){
			$result = $e->getMessage();
		}
		filedebug('ios推送Tags','./log/app_push.php');
		filedebug($result,'./log/app_push.php');

		//推送成功执行入库操作
		if($result['http_code'] === 200){
			$params = array(
				'title' => $title,
				'content' => $client,
				'nodeid' => $nodeid
			);
			$data = serialize($params);
		}
	}

	/**
	 * @param $title  推送标题
	 * @param $content 推送内容
	 * @param $nodeid  推送Tag为 nodeid
	 * @param $extras  推送扩展参数
	 * Tag推送   AddTag为用户Node_id
	 * 如果客户端没有tag值为空极光服务端会抛出cannot find user by this audience
	 */
	public function push_tags($title,$content,$nodeid,$extras){
		filedebug($title,'./log/app_push.php'); //标题
		filedebug($content,'./log/app_push.php'); //内容

		/**
		 *	扩展参数 key => value
		 *	数据结构体
		 *	data=>{
		 *		"type": 2   type=1  优惠卷  type=2 红包  type=3 充值列表  type =4站内信列表
		 *		"packet": {
		 *			"create_time": "2016-11-18 10:31:17",
		 *			"end_time": "2016-11-19 10:31:18",
		 *			"id": "30985",
		 *			"income": ".01",
		 *			"node_id": "29820",
		 *			"numrow": "1",
		 *			"remarks": "普通红包",
		 *			"short_title": "",
		 *			"status": "0",
		 *			"title": "线下买单赠送红包",
		 *			"type": "1"
		 *		},
		 *	}
		 **/

		$nodeid .= '';
		$jpush = C('JPUSH');
		Vendor('JPush.Client');
		//默认日志路径为 ./jpush.log,即保存在当前运行目录，如果想关闭日志，可以指定为 null
		$client = new \JPush\Client($jpush['app_key'],$jpush['secret'],null);
		$push = $client->push();
		try {
			$push->setPlatform('all');
			$push->addTag($nodeid);
			$push->setNotificationAlert($content);
			//ios
			$push->iosNotification($content, [
				'sound' => 'sound',
				'badge' => '+1',
				'extras' => $extras,
				'available' => true,
			]);

			//安卓
			$push->androidNotification($content, [
				'sound' => 'sound',
				'badge' => '+1',
				'extras' => $extras,
				'available' => true,
				'title' => $title,//推送标题
				'builder_id' => 0,
				//'content-available' => 1, //为1表示静默推送
			]);

			$push->options(array(
				"sendno" => time(),
				"time_to_live" => 86400, //保存离线时间的秒数默认为一天
			));

			$result = $push->send();
			filedebug("nodeid = ".$nodeid,'./log/app_push.php');
			filedebug($result,'./log/app_push.php');
		}catch (\Exception $e){
			$result = $e->getMessage();
			filedebug("nodeid = ".$nodeid,'./log/app_push.php');
			filedebug($result,'./log/app_push.php');
		}
	}


}